
//
//  TIMChatMessageViewController.m
//  Demo_sdk
//
//  Created by Deli Xia on 2018/6/29.
//  Copyright © 2018年 Deli Xia. All rights reserved.
//

#import "TIMChatMessageViewController.h"
#import "Masonry.h"
#import "TIMDemoMacro.h"
#import "TIMMessageBaseCell.h"
#import "TIMTextMessageCell.h"
#import "TIMSystemMessageCell.h"
#import "TIMGroupDetailVC.h"
#import "TIMFriendDetailVC.h"
#import "ProgressHUD.h"
#import "TIMCustomMenu.h"
#import "TIMSnapshotTextMessageCell.h"
#import "TIMInviteViewController.h"

#import "TIMMessage.h"
#import "TIMStorageModel.h"
#import "TIMStorageManager.h"
#import "TIMCommon.h"
#import "TIMApi.h"

#import <UIKit/UIKit.h>

#define BACKGROUD_COLOR [UIColor colorWithRed:235/255.0 green:235/255.0 blue:235/255.0 alpha:1.0]

@interface TIMChatMessageViewController ()<UITextFieldDelegate,UITableViewDelegate,UITableViewDataSource,TIMMessageViewCellDelegate>

@property (nonatomic, strong) UITextField *inputView;
@property (nonatomic, strong) UIView *tabbarView;
@property (nonatomic, strong) UIButton *afterBurnBtn;
@property (nonatomic, strong) TIMCustomMenu *menuView;
@property (nonatomic, assign) BOOL isAfterBurn;

@property (nonatomic, strong) UITableView *chatMessageView;

@property (nonatomic, strong) NSMutableArray *dataSource;

@property (nonatomic, strong) TIMUserInfo *userInfo;
@property (nonatomic, strong) TIMGroupInfo *groupInfo;
@property (nonatomic, strong) TIMMessage *message;  // 标志着上层当前要加入数据的消息

@property (nonatomic, strong) UIRefreshControl *refreshControl;     // 下拉刷新
@property (nonatomic, strong) NSDate *currentDate;
@property (nonatomic, assign) BOOL isScrollBottom;

@property (nonatomic, strong) NSMutableArray *inviteArray;

@property (nonatomic, assign) BOOL hasMore;

@end

@implementation TIMChatMessageViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = RGBColor(249, 249, 249);
    self.currentDate = [NSDate date];
    self.isScrollBottom = YES;
    [self setupData];
    [self setUpNav];
    [self setupUI];
    [self getLocalHistoryMessage];
    
    self.refreshControl = [[UIRefreshControl alloc] init];
    self.refreshControl.attributedTitle = [[NSAttributedString alloc] initWithString:@"努力加载中……"];
    self.refreshControl.tintColor = UIColor.redColor;
    [self.refreshControl addTarget:self action:@selector(refresh:) forControlEvents:(UIControlEvents)UIControlEventValueChanged];
    [self.chatMessageView addSubview:self.refreshControl];
    // 设置虚拟键盘监听器
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveMsg:) name:TIM_FROM_SERVER_MESSAGE_BROADCAST object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reveiceRevokeMsg:) name:TIM_REVOKE_MESSAGE_BROADCAST object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateMsgList:) name:TIM_OPERATION_GROUP_BROADCAST object:nil];
    
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateMsgList:) name:TIM_FINISH_LOGIN_SYNC_SERVER_BROADCAST object:nil];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    self.isScrollBottom = NO;
}

-(void)refresh:(UIRefreshControl*)sender {
    if (_hasMore) {
        [self getLocalHistoryMessage];
    } else {
        [self queryHistoryMessageFromServer];
    }
    
    [self performSelector:@selector(refreshOver:) withObject:nil afterDelay:3];
}

-(void)refreshOver:(NSString*)result {
    [self.chatMessageView reloadData];
    //刷新完成停止刷新
    [self.refreshControl endRefreshing];
}

#pragma mark - notification

- (void)updateMsgList:(NSNotification *)noti {
    NSDictionary *userInfo = noti.userInfo;
    TIMMessage *messageInfo = [userInfo valueForKey:@"message"];
    
    switch ([[userInfo valueForKey:@"operateGroupType"] integerValue]) {
        case TIMOperateGroupTypeCreateGroup:
            NSLog(@"操作群组：TIMOperateGroupTypeCreateGroup");
            break;
        case TIMOperateGroupTypeOfferGroup:
            NSLog(@"操作群组：TIMOperateGroupTypeOfferGroup");
            break;
     
        case TIMOperateGroupTypeExitGroup:
            NSLog(@"操作群组：TIMOperateGroupTypeExitGroup");
            break;
        case TIMOperateGroupTypeModifyGroupName:
            NSLog(@"操作群组：TIMOperateGroupTypeModifyGroupName");
            break;
        case TIMOperateGroupTypeDismissGroup:
            NSLog(@"操作群组：TIMOperateGroupTypeDismissGroup");
            break;
        case TIMOperateGroupTypeModifyMemoGroup:
            NSLog(@"操作群组：TIMOperateGroupTypeModifyMemoGroup");
            break;
        case TIMOperateGroupTypeStopTalkGroup:
            NSLog(@"操作群组：TIMOperateGroupTypeStopTalkGroup");
            break;
        case TIMOperateGroupTypeOpenTalkGroup:
            NSLog(@"操作群组：TIMOperateGroupTypeOpenTalkGroup");
            break;

        case TIMOperateGroupTypeTransferOwner:
            NSLog(@"操作群组：TIMOperateGroupTypeTransferOwner");
            break;
        case TIMOperateGroupTypeAddAdminGroup:
            NSLog(@"操作群组：TIMOperateGroupTypeAddAdminGroup");
            break;
        case TIMOperateGroupTypeDeleteAdminGroup:
            NSLog(@"操作群组：TIMOperateGroupTypeDeleteAdminGroup");
            break;
        case TIMOperateGroupTypeRemoveGroup:
            NSLog(@"操作群组：TIMOperateGroupTypeKickOff");
            break;
        case TIMOperateGroupTypeGroupOfferStop:
            NSLog(@"操作群组：TIMOperateGroupTypeGroupOfferStop");
            break;
        case TIMOperateGroupTypeGroupOfferOpen:
            NSLog(@"操作群组：TIMOperateGroupTypeGroupOfferOpen");
            break;
        case TIMOperateGroupTypeGrpOfferAuditCommit:
            NSLog(@"操作群组：TIMOperateGroupTypeGroupOfferOpen");
            [self setupInviteWaitACKMessage:messageInfo];
            break;
        default:
            break;
    }
    
    dispatch_async(dispatch_get_main_queue(), ^{
        if (messageInfo.friendID == self.userInfo.userID || messageInfo.groupID == self.groupInfo.groupID) {
            [self.dataSource addObject:messageInfo];
            [self getLocalHistoryMessage];
            [self.chatMessageView reloadData];
        }
    });
}

- (void)setupInviteWaitACKMessage:(TIMMessage *)message {
    NSString *text = [NSString stringWithFormat:@"%@ 去确认",message.text];
    
    
}

- (void)receiveMsg:(NSNotification *)noti {
    NSDictionary *dic = noti.userInfo;
    // 收到消息后标志消息为已读
    if (self.userInfo) {
        [[TIMStorageManager sharedStorageManager] readConversionByPartnerId:self.userInfo.userID];
    } else {
        [[TIMStorageManager sharedStorageManager] readConversionByPartnerId:self.groupInfo.groupID];
    }
   
    TIMMessage *messageInfo = dic[@"message"];
    
    dispatch_async(dispatch_get_main_queue(), ^{
        if (messageInfo.friendID == self.userInfo.userID || messageInfo.groupID == self.groupInfo.groupID) {
            [self.dataSource addObject:messageInfo];
            [self.chatMessageView reloadData];
        }
    });
}

- (void)reveiceRevokeMsg:(NSNotification *)noti {
      NSDictionary *dic = noti.userInfo;
    if (self.userInfo) {
        [[TIMStorageManager sharedStorageManager] readConversionByPartnerId:self.userInfo.userID];
    } else {
        [[TIMStorageManager sharedStorageManager] readConversionByPartnerId:self.groupInfo.groupID];
    }
    
    TIMMessage *messageInfo = dic[@"message"];
    dispatch_async(dispatch_get_main_queue(), ^{
        if (messageInfo.friendID == self.userInfo.userID || messageInfo.groupID == self.groupInfo.groupID) {
            [self.dataSource replaceObjectAtIndex:self.dataSource.count - 1 withObject:messageInfo];
            [self.chatMessageView reloadData];
        }
    });
}

- (void)setUpNav {
    self.view.backgroundColor = UIColor.whiteColor;
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame = CGRectMake(0, 0, 65, 25);
    btn.titleLabel.font = TPSFontSize(15);
    if (self.userInfo) {
        [btn setImage:[UIImage imageNamed:@"IM_User_infoImg"] forState:UIControlStateNormal];
    } else if (self.groupInfo) {
         [btn setImage:[UIImage imageNamed:@"Group_infoImg"] forState:UIControlStateNormal];
    }
   
    [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(infoClicked) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:btn];
}

- (void)infoClicked {
    if (self.userInfo) {
        TIMFriendDetailVC *vc = [TIMFriendDetailVC new];
        vc.friendID = self.userInfo.userID;
        [self.navigationController pushViewController:vc animated:YES];
    } else if (self.groupInfo) {
        TIMGroupDetailVC *vc = [TIMGroupDetailVC new];
        vc.groupID = self.groupInfo.groupID;
        [self.navigationController pushViewController:vc animated:YES];
    }
}

- (void)setupData {
    if ([self.messagePartner isKindOfClass:[TIMUserInfo class]]) {
        self.userInfo = (TIMUserInfo *)self.messagePartner;
        TIMConversationInfo *conversion = [[TIMStorageManager sharedStorageManager] getSingleConversionByPartnerID:self.userInfo.userID];
        if ([conversion.afterRea isEqualToString:@"YES"]) {
            self.isAfterBurn = YES;
        } else {
            self.isAfterBurn = NO;
        }
    } else {
        self.groupInfo = (TIMGroupInfo *)self.messagePartner;
        TIMConversationInfo *conversion = [[TIMStorageManager sharedStorageManager] getSingleConversionByPartnerID:self.groupInfo.groupID];
        if ([conversion.afterRea isEqualToString:@"YES"]) {
            self.isAfterBurn = YES;
        } else {
            self.isAfterBurn = NO;
        }
    }
    self.dataSource = [NSMutableArray array];
}

- (void)setupUI {
    [self.view addSubview:self.chatMessageView];
    [self.view addSubview:self.tabbarView];
    [self.tabbarView addSubview:self.inputView];
    [self.tabbarView addSubview:self.afterBurnBtn];

    [self.tabbarView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.and.right.bottom.mas_equalTo(self.view);
        make.height.mas_greaterThanOrEqualTo(49.0);
    }];
    [self.chatMessageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.and.left.right.mas_equalTo(self.view);
        make.bottom.mas_equalTo(self.inputView.mas_top);
    }];
    [self.inputView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.and.top.bottom.mas_equalTo(self.tabbarView);
        make.right.equalTo(self.tabbarView).offset(-49.0);
    }];
    [self.afterBurnBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.and.top.bottom.mas_equalTo(self.tabbarView);
        make.left.mas_equalTo(self.inputView.mas_right);
    }];
}

- (void)viewSafeAreaInsetsDidChange {
    [super viewSafeAreaInsetsDidChange];
    [self.chatMessageView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.and.left.and.right.mas_equalTo(self.view);
        make.bottom.mas_equalTo(self.inputView.mas_top);
    }];
    
    [self.tabbarView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.and.right.mas_equalTo(self.view);
        make.height.mas_greaterThanOrEqualTo(49.0);
        make.bottom.mas_equalTo(-self.view.safeAreaInsets.bottom);
    }];
}

#pragma mark - 监听事件
- (void) keyboardWillChangeFrame:(NSNotification *) note {
    // 1.取得弹出后的键盘frame
    CGRect keyboardFrame = [note.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    
    // 2.键盘弹出的耗时时间
    CGFloat duration = [note.userInfo[UIKeyboardAnimationDurationUserInfoKey] floatValue];
    
    // 3.键盘变化时，view的位移，包括了上移/恢复下移
    CGFloat transformY = keyboardFrame.origin.y - self.view.frame.size.height;
    
    [UIView animateWithDuration:duration animations:^{
        self.view.transform = CGAffineTransformMakeTranslation(0, transformY);
    }];
}

#pragma mark - 手势

- (void)messageCellLongPress:(TIMMessage *)message rect:(CGRect)rect {
    
    NSInteger row = [self.dataSource indexOfObject:message];
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:row inSection:0];
    CGRect cellRect = [self.chatMessageView rectForRowAtIndexPath:indexPath];
    rect.origin.y += cellRect.origin.y - self.chatMessageView.contentOffset.y;
    
    if (self.userInfo) {
        [self.menuView showInView:self.view withMessage:message rect:rect actionBlock:^(TPSChatMenuItemType type) {
            if (type == TPSChatMenuItemTypeDelete) {
                [TIMApi deleteMessage:message isGroup:0 completion:^(NSError *error) {
                    if (!error) {
                        dispatch_async(dispatch_get_main_queue(), ^{
                            [self.dataSource removeObject:message];
                            [self.chatMessageView reloadData];
                        });
                    } else {
                        [ProgressHUD showHudTipStr:@"删除失败"];
                    }
                }];
            } else if (type == TPSChatMenuItemTypeRevoke) {
                [TIMApi revokeMessage:message isGroup:0 completion:^(NSError *error) {
                    if (!error) {
                        dispatch_async(dispatch_get_main_queue(), ^{
                            
                            NSDictionary *historyMessage = [[TIMStorageManager sharedStorageManager] getMessageRecordForPartnerID:self.groupInfo.groupID date:[NSDate date] count:1];
                            NSArray *data = [historyMessage valueForKey:@"message"];
                            [self.dataSource removeObject:message];
                            [self.dataSource addObject:data[0]];
                            [self.chatMessageView reloadData];
                        });
                    } else {
                        [ProgressHUD showHudTipStr:@"撤回失败"];
                    }
                }];
            }
        }];
    } else if (self.groupInfo) {
        [self.menuView showInView:self.view withMessage:message rect:rect actionBlock:^(TPSChatMenuItemType type) {
            if (type == TPSChatMenuItemTypeDelete) {
                [TIMApi deleteMessage:message isGroup:1 completion:^(NSError *error) {
                    if (!error) {
                        dispatch_async(dispatch_get_main_queue(), ^{
                            [self.dataSource removeObject:message];
                            [self.chatMessageView reloadData];
                        });
                    } else {
                        [ProgressHUD showHudTipStr:@"删除失败"];
                    }
                }];
            } else if (type == TPSChatMenuItemTypeRevoke) {
               [TIMApi revokeMessage:message isGroup:1 completion:^(NSError *error) {
                    if (!error) {
                        dispatch_async(dispatch_get_main_queue(), ^{
                            
                            NSDictionary *historyMessage = [[TIMStorageManager sharedStorageManager] getMessageRecordForPartnerID:self.groupInfo.groupID date:[NSDate date] count:1];
                            NSArray *data = [historyMessage valueForKey:@"message"];
                            [self.dataSource removeObject:message];
                            [self.dataSource addObject:data[0]];
                            //
                            [self.chatMessageView reloadData];
                        });
                    } else {
                        [ProgressHUD showHudTipStr:@"撤回失败"];
                    }
               }];
            }
        }];
    }
}

- (void)messageCellTap:(TIMMessage *)message {
    if (message.messageType == TIMMessageTypeSnapshotText && message.ownerTyper == TIMMessageOwnerTypeFriend) {
        [TIMApi touchUpMessage:message messageType:TIMMessageTypeSnapshotText clickState:TIMMessageDidClick];
        [self.chatMessageView reloadData];
    }
}

- (void)messageCellTOCinform:(TIMMessage *)message {
    if (message.operateGroupType == TIMOperateGroupTypeGrpOfferAuditCommit) {
        TIMInviteViewController *inviteVC = [TIMInviteViewController new];
        inviteVC.groupInfo = [[TIMStorageManager sharedStorageManager] getInviteUserGroupInfoByGroupId:message.groupID messageKey:[NSString stringWithFormat:@"%ld",(long)message.msgKey]];
        [self.navigationController pushViewController:inviteVC animated:YES];
        [TIMApi touchUpMessage:message messageType:TIMMessageTypeText clickState:TIMMessageDidClick];
    }
}

#pragma mark - TableviewDelegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (self.isScrollBottom) {
        dispatch_after(0.005, dispatch_get_main_queue(), ^{
            if (self.dataSource.count >0) {
                [self.chatMessageView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:self.dataSource.count - 1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:NO];
            }
        });
    }
    return self.dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {   
    TIMMessage * message = self.dataSource[indexPath.row];
    if (message.messageType == TIMMessageTypeText) {
        TIMTextMessageCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TIMTextMessageCell"];
        [cell setMessage:message];
        cell.delegate = self;
        return cell;
    } else if (message.messageType == TIMMessageTypeSnapshotText) {
        TIMSnapshotTextMessageCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TIMSnapshotTextMessageCell"];
        [cell setMessage:message];
        cell.delegate = self;
        return cell;
    } else {
        TIMSystemMessageCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TIMSystemMessageCell"];
        [cell setMessage:message];
        cell.delegate = self;
        return cell;
    }
}


#pragma mark - TextFieldDelegate

/** 回车响应事件 */
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    // 我方发出信息
    // 发送消息默认是成功的，失败会回调给上层，成功不回调。
    [self sendMessageWithContent:textField.text completion:^(NSError *error) {
        if (error) {
            self.message.sendState = TIMMessageSendFail;
            if (error.code == 51003114) {
                [ProgressHUD showHudTipStr:@"你不是该群成员"];
            } else {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self.dataSource removeObject:self.message];
                    [self.chatMessageView reloadData];
                });
               [ProgressHUD showHudTipStr:@"发送失败"];
            }
        } else {
            dispatch_async(dispatch_get_main_queue(), ^{
                self.message.sendState = TIMMessageSendSuccess;
                NSDictionary *historyMessage = nil;
                // 从数据库获取最后一条消息，加入到上层
                if (self.groupInfo) {
                     historyMessage = [[TIMStorageManager sharedStorageManager] getMessageRecordForPartnerID:_groupInfo.groupID date:[NSDate date] count:1];
                } else if (self.userInfo) {
                     historyMessage = [[TIMStorageManager sharedStorageManager] getMessageRecordForPartnerID:_userInfo.userID date:[NSDate date] count:1];
                }
                NSArray *data = [historyMessage valueForKey:@"message"];
                [self.dataSource removeObject:self.message];
                [self.dataSource addObject:data[0]];
                [self.chatMessageView reloadData];
                 [self.chatMessageView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:self.dataSource.count - 1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:NO];
            });
        }
    }];
    // 消除消息框内容
    UITextView *view = [self.inputView viewWithTag:111];
    view.text = nil;
    [view resignFirstResponder];
    return YES; // 返回值意义不明
}

// 发送消息
- (void) sendMessageWithContent:(NSString *) text completion:(nullable void (^)(NSError *error))completion {
    
    TIMMessage *message = [[TIMMessage alloc] init];
    message.text = text;
    message.showTime = YES;
    if (self.userInfo) {
        message.partnerType = TIMPartnerTypeUser;
        message.friendID = self.userInfo.userID;
        message.sendState = TIMMessageSending;
        if (self.isAfterBurn) {
             message.messageType = TIMMessageTypeSnapshotText;
            [TIMApi sentMessage:message content:text isGroup:0 msgSnapshot:YES aateArray:nil completion:completion];
        } else {
             message.messageType = TIMMessageTypeText;
            [TIMApi sentMessage:message content:text isGroup:0 msgSnapshot:NO aateArray:nil completion:completion];
        }
    } else if (self.groupInfo) {
        message.partnerType = TIMPartnerTypeGroup;
        message.groupID = self.groupInfo.groupID;
        message.friendID = self.groupInfo.groupID;
        message.sendState = TIMMessageSending;
        if (self.isAfterBurn) {
             message.messageType = TIMMessageTypeSnapshotText;
            [TIMApi sentMessage:message content:text isGroup:1 msgSnapshot:YES aateArray:nil completion:completion];
        } else {
             message.messageType = TIMMessageTypeText;
            [TIMApi sentMessage:message content:text isGroup:1 msgSnapshot:NO aateArray:nil completion:completion];
        }
        
    }
    self.message = message;
    [self.dataSource addObject:self.message];
}


#pragma mark --- time
static NSTimeInterval lastDateInterval = 0;
static NSInteger msgAccumulate = 0;
- (BOOL)p_needShowTime:(NSDate *)date
{
    if ( date.timeIntervalSince1970 - 0 > 600) {
        lastDateInterval = date.timeIntervalSince1970;
        msgAccumulate = 0;
        return YES;
    }
    return NO;
}

#pragma mark - SetupData

// 获取本地历史消息 前20条 （从数据库内取）

- (void)getLocalHistoryMessage {
    if ([self.messagePartner isKindOfClass:[TIMUserInfo class]]) {
        self.userInfo = (TIMUserInfo *)self.messagePartner;
        self.title = self.userInfo.showName;
        NSDictionary *historyMessage = [[TIMStorageManager sharedStorageManager] getMessageRecordForPartnerID:_userInfo.userID date:self.currentDate count:20];
        NSArray *data = [historyMessage valueForKey:@"message"];
        [self.dataSource insertObjects:data atIndexes:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, data.count)]];
        self.hasMore = [[historyMessage valueForKey:@"isMore"] boolValue];
   
//        mes.imagePath = @"erere";
        
        if (data.count) {
            self.currentDate = [data[0] date];
        }
       
        NSTimeInterval tm = 0;
        int count = 0;
        // 时间是否要显示
        for (TIMMessage *message in self.dataSource) {
            if (message.messageType != TIMMessageTypeOther) {
                if (message.date.timeIntervalSince1970 - tm > 600) {
                    tm = message.date.timeIntervalSince1970;
                    count = 0;
                    message.showTime = YES;
                    lastDateInterval =  message.date.timeIntervalSince1970;
                }
            }
        }
        
    } else {
        self.groupInfo = (TIMGroupInfo *)self.messagePartner;
        self.title = self.groupInfo.groupName;
        NSDictionary *historyMessage = [[TIMStorageManager sharedStorageManager] getMessageRecordForPartnerID:_groupInfo.groupID date:self.currentDate count:20];
        NSArray *data = [historyMessage valueForKey:@"message"];

        [self.dataSource insertObjects:data atIndexes:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, data.count)]];
        self.hasMore = [[historyMessage valueForKey:@"isMore"] boolValue];
        

        if (data.count) {
            self.currentDate = [data[0] date];
        }
        
        NSTimeInterval tm = 0;
        int count = 0;
        // 时间是否要显示
        for (TIMMessage *message in self.dataSource) {
            if (message.messageType != TIMMessageTypeOther) {
                if (message.date.timeIntervalSince1970 - tm > 600) {
                    tm = message.date.timeIntervalSince1970;
                    count = 0;
                    message.showTime = YES;
                    lastDateInterval =  message.date.timeIntervalSince1970;
                }
            }
        }
    }
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.chatMessageView reloadData];
    });
    
}

- (void)queryHistoryMessageFromServer {
      TIMMessage *message = self.dataSource.firstObject;
    if ([self.messagePartner isKindOfClass:[TIMUserInfo class]]) {
        [TIMApi queryHistoryMessageWithlimit:20 msgSender:message.friendID msgKey:message.msgKey msgGlobalId:message.globalID completion:^(NSError *error) {
            if (!error) {
                // 查询成功后保存到了数据库，请再从历史取
                NSLog(@"从服务器查询历史消息成功");
                [self getLocalHistoryMessage];
            }
        }];
    } else {
        [TIMApi queryHistoryMessageWithlimit:20 msgSender:message.groupID msgKey:message.msgKey msgGlobalId:message.globalID completion:^(NSError *error) {
            if (!error) {
                // 查询成功后保存到了数据库，请再从历史取
                NSLog(@"从服务器查询历史消息成功");
                [self getLocalHistoryMessage];
            }
        }];
    }
}

- (void)clickAfterBurn {
    
    self.afterBurnBtn.selected = !self.isAfterBurn;
    self.isAfterBurn = !self.isAfterBurn;
    if (self.userInfo) {
        [TIMApi setupBurnAfterReadBySessionid:self.userInfo.userID isBurn:self.isAfterBurn];
    } else if (self.groupInfo) {
        [TIMApi setupBurnAfterReadBySessionid:self.groupInfo.groupID isBurn:self.isAfterBurn];
    }
}

#pragma mark - Getter

- (UITableView *)chatMessageView {
    if (!_chatMessageView) {
        _chatMessageView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 60) style:UITableViewStylePlain];
        _chatMessageView.delegate = self;
        _chatMessageView.dataSource = self;
        _chatMessageView.backgroundColor = BACKGROUD_COLOR;
        _chatMessageView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_chatMessageView setAllowsSelection:NO];
        _chatMessageView.rowHeight = 100;
        [_chatMessageView registerClass:[TIMTextMessageCell class] forCellReuseIdentifier:@"TIMTextMessageCell"];
        [_chatMessageView registerClass:[TIMSystemMessageCell class] forCellReuseIdentifier:@"TIMSystemMessageCell"];
        [_chatMessageView registerClass:[TIMSnapshotTextMessageCell class] forCellReuseIdentifier:@"TIMSnapshotTextMessageCell"];
    }
    return _chatMessageView;
}

- (UIView *)tabbarView {
    if (!_tabbarView) {
        _tabbarView = [[UIView alloc] init];
        _tabbarView.backgroundColor = UIColor.whiteColor;
    }
    return _tabbarView;
}

- (UITextField *)inputView {
    if (!_inputView) {
        _inputView = [[UITextField alloc] init];
        _inputView.tag = 111;
        _inputView.leftViewMode = UITextFieldViewModeAlways;
        _inputView.delegate = self;
        _inputView.placeholder = @"请输入要发送的信息";
        _inputView.backgroundColor = [UIColor whiteColor];
        _inputView.borderStyle = UITextBorderStyleRoundedRect;
    }
    return _inputView;
}

- (UIButton *)afterBurnBtn {
    if (!_afterBurnBtn) {
        _afterBurnBtn = [UIButton buttonWithType:UIButtonTypeSystem];
        _afterBurnBtn.backgroundColor = UIColor.whiteColor;
        _afterBurnBtn.selected = self.isAfterBurn;
        [_afterBurnBtn setTitle:@"开启" forState:UIControlStateNormal];
        [_afterBurnBtn setTitle:@"关闭" forState:UIControlStateSelected];
        [_afterBurnBtn setTitleColor:UIColor.blackColor forState:UIControlStateNormal];
        [_afterBurnBtn addTarget:self action:@selector(clickAfterBurn) forControlEvents:UIControlEventTouchUpInside];
    }
    return _afterBurnBtn;
}

- (TIMCustomMenu *)menuView {
    if (!_menuView) {
        _menuView = [TIMCustomMenu new];
        _menuView.backgroundColor = UIColor.blackColor;
    }
    return _menuView;
}

- (NSMutableArray *)inviteArray {
    if (!_inviteArray) {
        _inviteArray = [NSMutableArray array];
    }
    return _inviteArray;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
